/*
* 工位人员管理模块
*/
const express = require('express');
const router = express.Router();
// 引入数据库
const db = require("../../../config/db");
// 引入时间包
const moment = require("moment");
// 引入方法库
const { toCamelCase, toUnderlineCase, verifyToken} = require("../../../config/utils");
// 引入日志
const log = require("../../log");

// 获取所有工位人员列表
router.get("/list", async (req, res) => {
    console.log("===========获取工位人员列表接口============");
    // 获取参数
    let { pageNum, pageSize, workstationId } = req.query;
    // 拼接sql语句
    let sql = "select * from md_workstation_worker";
    let sql_where = ` where 1=1`;
    if(workstationId){
        sql_where += ` and workstation_id like '%${workstationId}%'`;
    }
    if(workstationId){
        sql += sql_where;
    }
    
    // 分页
    sql += ` limit ${(pageNum-1)*pageSize}, ${pageSize}`;
    // 查询数据库
    db.query("查询工位人员列表", sql, (err, result)=>{
        if(err){
            res.send({code: 500, msg: "查询工位人员列表失败", data: err});
            return;
        }
        // 查询总数
        db.query("查询工位人员总数", `select count(*) as count from md_workstation_worker ${sql_where}`, (err, count)=>{
            if(err){
                res.send({code: 500, msg: "查询工位人员总数失败", data: err});
                return;
            }
            if(result.length > 0){
                 // 变量Json数组key转成下划线第一个大写
                 result = result.map(item => {
                    return toCamelCase(item)
                })
                res.send({code: 200, msg: "查询工位人员列表成功", rows: result, total: count[0].count});
            }else{
                res.send({code: 200, msg: "查询工位人员列表成功", rows: [], total: 0});
            }
        })
    })
})

// 添加工位人员
router.post("/", async (req, res) => {
    console.log("===========添加工位人员接口============");
    // 获取参数
    let { workstationId, postId, postName, quantity } = req.body;
     // 获取创建人
     let {username} = verifyToken(req.headers.authorization);
     // 获取创建时间
     let createTime = moment().format("YYYY-MM-DD HH:mm:ss");
     // 判断岗位是否添加到工位上
     db.query("查询岗位是否添加到工位上", `select * from md_workstation_worker where post_id = '${postId}'`, (err, result)=>{
        if(err){
            res.send({code: 500, msg: "查询岗位是否添加到工位上失败", data: err});
            return;
        }
        if(result.length > 0){
            // 查询工位名称
            db.query("查询工位名称", `select workstation_name from md_workstation where workstation_id = '${workstationId}'`, (err, workstation_name_result)=>{
                if(err){
                    res.send({code: 500, msg: "查询工位名称失败", data: err});
                    return;
                }
                res.send({code: 500, msg: `当前岗位已分配至工作站：[ ${workstation_name_result[0].workstation_name} ]上`});
            })
            return;
        }
        // 根据岗位id查询岗位名称
        db.query("查询岗位名称", `select post_name from sys_post where post_id = '${postId}'`, (err, post_name_result)=>{
            if(err){
                res.send({code: 500, msg: "查询岗位名称失败", data: err});
                return;
            }
            if(post_name_result.length > 0){
                postName = post_name_result[0].post_name;
            }
            // 插入数据库
            let sql = `insert into md_workstation_worker ( workstation_id, post_id, post_name, quantity, create_by, create_time ) 
            values
            ('${workstationId}', '${postId}', '${postName}', '${quantity}', '${username}', '${createTime}')`;
            db.query("添加工位人员", sql, (err, result)=>{
                if(err){
                    res.send({code: 500, msg: "添加工位人员失败", data: err});
                    return;
                }
                if(result.affectedRows > 0){
                    res.send({code: 200, msg: "添加工位人员成功", data: []});
                }else{
                    res.send({code: 500, msg: "添加工位人员失败", data: []});
                }
            })
        })
       
     })
})

// 查询单个工位人员
router.get(/^\/(\d+)$/, (req, res) => {
    console.log("===========查询单个工位人员接口，正则匹配============");
    // 获取参数
    let url_arr = req.url.split("/");
    const id = url_arr[url_arr.length - 1];
   
    db.query("查询单个工位人员", `select * from md_workstation_worker where record_id = ${id}`, (err, result)=>{
        if(err){
            res.send({code: 500, msg: "查询单个工位人员失败", data: err});
            return;
        }
        if(result.length > 0){
            // 变量Json数组key转成下划线第一个大写
            result = result.map(item => {
                return toCamelCase(item)
            })
            res.send({code: 200, msg: "查询单个工位人员成功", data: result[0]});
        }else{
            res.send({code: 500, msg: "查询单个工位人员失败"});
        }
    })
})

// 修改工位人员
router.put("/", async (req, res) => {
    console.log("===========修改工位人员接口============");
    // 获取参数
    let { workstationId, postId, postName, quantity, recordId } = req.body;
    // 获取修改人
    let {username} = verifyToken(req.headers.authorization);
    // 获取修改时间
    let updateTime = moment().format("YYYY-MM-DD HH:mm:ss");
    // 判断岗位是否修改到工位上
    db.query("查询岗位是否修改到工位上", `select * from md_workstation_worker where post_id = '${postId}' and record_id != ${recordId} `, (err, result)=>{
        if(err){
            res.send({code: 500, msg: "查询岗位是否修改到工位上失败", data: err});
            return;
        }
        if(result.length > 0){
            // 查询工位名称
            db.query("查询工位名称", `select workstation_name from md_workstation where workstation_id = '${workstationId}'`, (err, workstation_name_result)=>{
                if(err){
                    res.send({code: 500, msg: "查询工位名称失败", data: err});
                    return;
                }
                res.send({code: 500, msg: `当前岗位已分配至工作站：[ ${workstation_name_result[0].workstation_name} ]上`});
            })
            return;
        }
        // 根据岗位id查询岗位名称
        db.query("查询岗位名称", `select post_name from sys_post where post_id = '${postId}'`, (err, post_name_result)=>{
            if(err){
                res.send({code: 500, msg: "查询岗位名称失败", data: err});
                return;
            }
            if(post_name_result.length > 0){
                postName = post_name_result[0].post_name;
            }
            // 插入数据库
            let sql = `update md_workstation_worker set workstation_id = '${workstationId}', post_id = '${postId}', post_name = '${postName}', 
            quantity = '${quantity}', update_by = '${username}', update_time = '${updateTime}' 
            where record_id = ${recordId}`
            db.query("修改工位人员", sql, (err, result)=>{
                if(err){
                    res.send({code: 500, msg: "修改工位人员失败", data: err});
                    return;
                }
                if(result.affectedRows > 0){
                    res.send({code: 200, msg: "修改工位人员成功", data: []});
                }else{
                    res.send({code: 500, msg: "修改工位人员失败", data: []});
                }
            })
        })
    })
})

// 删除工位人员
router.delete("/:id", (req, res) => {
    console.log("===========删除工位人员接口============");
    // 获取参数
    let {id} = req.params;
     // 拼接sql,删除多条数据
     let sql = `delete from md_workstation_worker where record_id in(${id})`;
    // 查询数据库
    db.query("删除工位人员", sql, (err, result) => {
        if (err) {
            res.send({code: 500, msg: "删除工位人员失败", data: err});
            return
        }
        if(result.affectedRows > 0){
            res.send({code: 200, msg: "删除工位人员成功"})
        }else{
            res.send({code: 500, msg: "删除工位人员失败"})
        }
    })
})


module.exports = router;
